<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-11-13
 * Time: 10:02
 */

namespace app\app\controller;


use app\constant\OrderConst;
use app\helper\WxHelper;
use app\libs\Utils;
use app\model\AdminOrder;
use app\model\AdminTenant;
use app\model\AppWxUser;
use app\util\ReturnCode;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;

class Pay extends Base
{

    public function wxPay(){
        $order_id = $this->request->param('order_id');
        if(Utils::isEmpty($order_id)){
            return $this->buildFailed(ReturnCode::FAILED,'无效的订单');
        }
        $order = AdminOrder::get($order_id);
        if(!$order){
            return $this->buildFailed(ReturnCode::FAILED,'无此订单数据');
        }
        //判断一下订单状态
        if($order->trade_status!==OrderConst::ORDER_STATUS_NORMAL){
            return $this->buildFailed(ReturnCode::FAILED,'订单状态已变更，不允许支付');
        }
        $orderData = $order->getData();
        $siteData = AdminTenant::get($this->getUserTid(),null,true)->getData();
        $userData = AppWxUser::get($orderData['uid'],null,true)->getData();
        $result = WxHelper::getWxPayConfig($this->getUserTid(),$this->request);
        if(!$result['done']){
            return  $this->buildFailed(ReturnCode::FAILED,$result['msg']);
        }
        $config = $result['config'];
        $attach = ['order_type'=>OrderConst::TYPE_GOODS,'tid'=>$siteData['id']];
        $app = Factory::payment($config);
        try {
            $result = $app->order->unify([
                'body' => $siteData['name'],
                'attach' => json_encode($attach),
                'out_trade_no' => isset($orderData['out_trade_no'])?$orderData['out_trade_no']:$orderData['id'].'_'.(time()),
                'total_fee' => $orderData['pay_amount'],
//                'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => $this->request->domain() . '/admin/Notify/wxPayNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $userData['openid'],
            ]);
            //这里可以生成多种配置，下面这种是jssdk的配置
            $jssdk = $app->jssdk;
            $result = $jssdk->sdkConfig($result['prepay_id']);
            return $this->buildSuccess($result);
        } catch (InvalidConfigException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED,'生成支付订单失败');
    }

    public function getPayReuslt(){
        $order_id = $this->request->param('order_id');
        if(Utils::isEmpty($order_id)){
            return $this->buildFailed(ReturnCode::FAILED,'无效的订单');
        }
        $order = AdminOrder::get($order_id);
        if(!$order){
            return $this->buildFailed(ReturnCode::FAILED,'无此订单数据');
        }
        $result=['pay_status'=>$order->pay_status,'type'=>$order->goods_type];
        return $this->buildSuccess($result);
    }
}